package com.ubuntuvim.threadframework.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;

import com.ubuntuvim.threadframework.Service;

public class ServiceImp implements Service {
	
	
	public void testThread() {
		//  如果使用的是synchronized(this)并不能带到锁的作用，
		//  因为每个线程的到的this对象都是不一样的
		synchronized (ServiceImp.class) {
		//  模拟一个数据库操作
			String filePath = "c:/test.txt";
			// 1. 先读取文件的数字
			String ctx = readTxtFile(filePath);
			System.out.println("线程【"+Thread.currentThread().getName()+"】，获取到的值是【"+ctx+"】");
			// 2. 数字相加
			int i = 0;
			if (!"".equals(ctx)) {
				i = Integer.parseInt(ctx);
				i += 1;
			}
			//  3.保存到文件里
			writeTxtFile((i+""), filePath);
		}
	}
	
	public static boolean writeTxtFile(String content, String filePath)  {
		RandomAccessFile mm = null;
		boolean flag = false;
		FileOutputStream o = null;
		try {
			o = new FileOutputStream(new File(filePath));
			o.write(content.getBytes("utf-8"));
			o.close();
			flag = true;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (mm != null) {
				try {
					mm.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return flag;
	}

	public static String readTxtFile(String filePath) {
		try {
			String encoding = "utf-8";
			File file = new File(filePath);
			if (file.isFile() && file.exists()) { // 判断文件是否存在
				InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);// 考虑到编码格式
				BufferedReader bufferedReader = new BufferedReader(read);
				String lineTxt = null;
				while ((lineTxt = bufferedReader.readLine()) != null) {
					//System.out.println(lineTxt);
					return lineTxt;
				}
				read.close();
			} else {
				System.out.println("找不到指定的文件");
			}
		} catch (Exception e) {
			System.out.println("读取文件内容出错");
			e.printStackTrace();
		}
		return "";
	}

}
